package org.zjvis.datascience.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zjvis.datascience.common.dto.OperatorFavouriteDTO;
import org.zjvis.datascience.common.exception.BaseErrorCode;
import org.zjvis.datascience.common.exception.DataScienceException;
import org.zjvis.datascience.common.util.JwtUtil;
import org.zjvis.datascience.service.mapper.OperatorFavouriteMapper;

import java.util.List;

/**
 * @description OperatorFavourite 收藏算子操作 Service
 * @date 2021-11-23
 */
@Service
public class OperatorFavouriteService {

    @Autowired
    private OperatorFavouriteMapper mapper;

    public List<OperatorFavouriteDTO> query() {
        long user = JwtUtil.getCurrentUserId();
        return mapper.selectStatus(user);
    }

    @Transactional(rollbackFor = Exception.class)
    public void favourite(OperatorFavouriteDTO dto) {
        try {
            mapper.insertSelective(dto);
        } catch (DuplicateKeyException e) {
            dto.setGmtCreator(JwtUtil.getCurrentUserId());
            mapper.delete(dto);
        }
    }

    public int delete(Long id) {
        OperatorFavouriteDTO dto = mapper.selectByPrimaryKey(id);
        if (dto == null) {
            return 0;
        }
        if (dto.getGmtCreator() != JwtUtil.getCurrentUserId()) {
            throw DataScienceException.of(BaseErrorCode.UNAUTHORIZED, "需收藏本人操作");
        }
        return mapper.deleteByPrimaryKey(id);
    }

}
